package com.chipcoo.email.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SendCloudEmailImpl {
    public  SendCloudEmailImpl(){
        apiUser="chipwing_test_1Gg7dK";
        apiKey = "0DwXwVnHm33Rljjx";
        from = "passport@chipcoo.com";
    }

    private String apiUser,apiKey,from,fromName;

    public String getApiKey() {
        return apiKey;
    }

    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }

    public String getApiUser() {
        return apiUser;
    }

    public void setApiUser(String apiUser) {
        this.apiUser = apiUser;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getFromName() {
        return fromName;
    }

    public void setFromName(String fromName) {
        this.fromName = fromName;
    }


    private HttpPost createHttpPost(String url,List<NameValuePair> params) throws UnsupportedEncodingException{
        HttpPost httpPost = new HttpPost(url);

        params.add(new BasicNameValuePair("apiUser", getApiUser()));
        params.add(new BasicNameValuePair("apiKey", getApiKey()));
        params.add(new BasicNameValuePair(
                "from",
                StringUtils.isBlank(getFromName())?getFrom():String.format("%s<%s>",getFromName(),getFrom())
        ));




        httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

        return  httpPost;

    }
    private String executePost(HttpPost httpPost) throws IOException{
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpPost);
        String szReturned = null;
        // 处理响应
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 正常返回, 解析返回数据
            szReturned = EntityUtils.toString(response.getEntity());
        } else {
            System.err.println("error");
        }
        httpPost.releaseConnection();

        return  szReturned;
    }
    public void send(String subject,String htmlContent,String... tos){
        if(null!=tos && tos.length>0) {
            StringBuilder rcpt_to = new StringBuilder();
            for (int i = 0; i < tos.length; i++) {
                String to = tos[i].trim();
                if (to.length() > 0) {
                    rcpt_to.append(to);
                    rcpt_to.append(';');
                }
            }
            if (rcpt_to.length() == 0) {

            } else {
                rcpt_to.deleteCharAt(rcpt_to.length() - 1);
            }
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("to", rcpt_to.toString()));
            params.add(new BasicNameValuePair("subject", subject));
            params.add(new BasicNameValuePair("html", htmlContent));
            try {
                executePost(createHttpPost("http://api.sendcloud.net/apiv2/mail/send", params));
            } catch (UnsupportedEncodingException ex) {

            } catch (IOException ex) {

            }

        }
    }

    public void sendTemplate(String templateInvokeName,Map<String,String> vars, String... tos){
        if(null!=tos && tos.length>0){

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            //params.add(new BasicNameValuePair("useAddressList", "true"));
            //params.add(new BasicNameValuePair("to", rcpt_to.toString()));
            params.add(new BasicNameValuePair("templateInvokeName", templateInvokeName));


            JSONObject jo = new JSONObject();
            jo.put("to",tos);
            if(null!=vars&&!vars.isEmpty()) {
                JSONObject joSub = new JSONObject();

                for (String key :
                        vars.keySet()) {
                    List<String> list = new ArrayList<>();
                    for(int i=0;i<tos.length;i++) list.add(vars.get(key));
                    joSub.put(String.format("%%%s%%", key),  list  );
                }

                jo.put("sub", joSub);
            }

            params.add(new BasicNameValuePair("xsmtpapi", jo.toString()));

            try {
                String szReturned = executePost(createHttpPost("http://api.sendcloud.net/apiv2/mail/sendtemplate", params));
                System.out.println(szReturned);
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
